import { NextFunction, Request, Response } from 'express'
import jwt from 'jsonwebtoken'
import { AppError } from '../utils/AppError'

interface AuthRequest extends Request {
  user?: {
    userId: string
    username: string
  }
}

export const authMiddleware = (req: AuthRequest, _res: Response, next: NextFunction) => {
  try {
    const token = req.headers.authorization?.split(' ')[1]

    if (!token) {
      throw new AppError(401, 'No token provided')
    }

    if (!process.env.JWT_SECRET) {
      throw new AppError(500, 'JWT_SECRET is not configured')
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET) as {
      userId: string
      username: string
    }

    req.user = decoded
    next()
  } catch (error) {
    next(new AppError(401, 'Invalid token'))
  }
}
